<template>
  <view class="todo-container">
    <view class="filter-bar">
      <u-tabs :list="statusList" :current="currentStatus" @change="onStatusChange"></u-tabs>
    </view>
    
    <search-box
      v-model="keyword"
      placeholder="搜索待办标题"
      @search="onSearch"
      @clear="onSearchClear"
      :show-action="true"
    ></search-box>
    
    <view class="todo-list">
      <u-empty v-if="todoList.length === 0" text="暂无待办事项" mode="list"></u-empty>
      <view v-else class="todo-item" v-for="(item, index) in todoList" :key="item.id" @click="viewTodo(item.id)">
        <view class="todo-title" :class="{'todo-completed': item.status === 2}">{{ item.title }}</view>
        <view class="todo-content" v-if="item.content">{{ item.content }}</view>
        <view class="todo-footer">
          <view class="todo-tags">
            <u-tag v-if="item.status === 0" text="待办" type="warning" size="mini" plain></u-tag>
            <u-tag v-else-if="item.status === 1" text="进行中" type="primary" size="mini" plain></u-tag>
            <u-tag v-else text="已完成" type="success" size="mini" plain></u-tag>
            
            <u-tag v-if="item.priority === 2" type="error" text="紧急" size="mini" plain style="margin-left: 10rpx;"/>
            <u-tag v-else-if="item.priority === 1" type="warning" text="重要" size="mini" plain style="margin-left: 10rpx;"/>
          </view>
          <text class="todo-time">{{ formatDeadline(item.deadline) }}</text>
        </view>
        <view class="todo-actions">
          <u-icon name="edit-pen" size="32" @click.stop="editTodo(item.id)"></u-icon>
          <u-icon name="trash" size="32" @click.stop="deleteTodoItem(item.id)"></u-icon>
        </view>
      </view>
    </view>
    
    <u-loadmore :status="loadMoreStatus" />
    
    <view class="add-btn">
      <u-button type="primary" icon="plus" shape="circle" @click="createTodo"></u-button>
    </view>
  </view>
</template>

<script>
import { getTodoPage, updateTodoStatus, deleteTodo } from '@/api/todo'
import { formatDeadline } from '@/utils/date'
import SearchBox from '@/components/common/SearchBox.vue'

export default {
  components: {
    SearchBox
  },
  data() {
    return {
      statusList: [
        { name: '全部' },
        { name: '待办' },
        { name: '进行中' },
        { name: '已完成' },
        { name: '已取消' }
      ],
      currentStatus: 0,
      todoList: [],
      page: 1,
      pageSize: 10,
      total: 0,
      keyword: '',
      loadMoreStatus: 'loadmore',
      isDeleting: false
    }
  },
  onLoad() {
    this.loadTodos()
  },
  onShow() {
    if (this.isDeleting) {
      this.isDeleting = false
      return
    }
    
    this.page = 1
    this.loadTodos()
  },
  onPullDownRefresh() {
    this.page = 1
    this.loadTodos().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  onReachBottom() {
    if (this.todoList.length < this.total) {
      this.page++
      this.loadMoreStatus = 'loading'
      this.loadTodos(true)
    }
  },
  methods: {
    formatDeadline,
    async loadTodos(append = false) {
      try {
        console.log('加载待办事项, 当前状态:', this.currentStatus, typeof this.currentStatus);
        
        const params = {
          page: this.page,
          pageSize: this.pageSize
        }
        
        // 处理状态过滤参数
        // 全部(0)不需要传status参数，其他状态需要传对应的值
        if (this.currentStatus > 0) {
          // 状态值转换：1->0(待办), 2->1(进行中), 3->2(已完成), 4->3(已取消)
          params.status = this.currentStatus - 1;
          console.log('添加状态过滤参数:', params.status);
        } else {
          console.log('不添加状态过滤参数，显示全部');
        }
        
        if (this.keyword && this.keyword.trim() !== '') {
          params.keyword = this.keyword
        }
        
        console.log('发送请求参数:', JSON.stringify(params));
        const res = await getTodoPage(params)
        
        if (append) {
          this.todoList = [...this.todoList, ...res.list]
        } else {
          this.todoList = res.list
        }
        
        this.total = res.total
        this.loadMoreStatus = this.todoList.length < this.total ? 'loadmore' : 'nomore'
      } catch (error) {
        console.error('获取待办事项列表失败', error)
        this.loadMoreStatus = 'loadmore'
      }
    },
    onStatusChange(e) {
      console.log('状态切换事件接收到的原始数据:', e);
      
      // u-tabs组件的change事件传递一个对象，包含index属性
      const index = e.index;
      
      // 确保index是有效的数字
      this.currentStatus = Number(index);
      console.log('设置当前状态为:', this.currentStatus, typeof this.currentStatus);
      
      this.page = 1;
      this.loadTodos();
    },
    viewTodo(id) {
      uni.navigateTo({
        url: `/pages/todo/detail?id=${id}`
      })
    },
    editTodo(id) {
      uni.navigateTo({
        url: `/pages/todo/edit?id=${id}`
      })
    },
    createTodo() {
      uni.navigateTo({
        url: '/pages/todo/edit'
      })
    },
    async deleteTodoItem(id) {
      // 设置删除标记，防止onShow中重复加载
      this.isDeleting = true
      
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个待办事项吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await deleteTodo(id)
              
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })
              
              // 重新加载数据
              this.page = 1
              this.loadTodos()
            } catch (error) {
              console.error('删除待办事项失败', error)
              // 删除失败时，重置删除标记
              this.isDeleting = false
            }
          } else {
            // 用户取消删除，重置删除标记
            this.isDeleting = false
          }
        }
      })
    },
    // 搜索
    onSearch() {
      this.page = 1
      this.loadTodos()
    },
    
    // 清除搜索
    onSearchClear() {
      this.keyword = ''
      this.page = 1
      this.loadTodos()
    }
  }
}
</script>

<style lang="scss" scoped>
.todo-container {
  padding: 20rpx;
  padding-top: 0;
  background-color: #f5f7fa;
  min-height: 100vh;
  
  .filter-bar {
    margin-bottom: 10rpx;
    background-color: #fff;
    border-bottom: none;
  }
  
  .todo-list {
    padding-top: 10rpx;
    
    .todo-item {
      position: relative;
      background-color: #fff;
      border-radius: 12rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      
      .todo-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 16rpx;
        padding-right: 80rpx;
        
        &.todo-completed {
          text-decoration: line-through;
          color: #999;
        }
      }
      
      .todo-content {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
        line-height: 1.5;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
      
      .todo-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .todo-tags {
          display: flex;
          flex-wrap: wrap;
        }
        
        .todo-time {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .todo-actions {
        position: absolute;
        top: 30rpx;
        right: 20rpx;
        display: flex;
        
        .u-icon {
          margin-left: 20rpx;
          opacity: 0.6;
          
          &:active {
            opacity: 1;
          }
        }
      }
    }
  }
  
  .add-btn {
    position: fixed;
    right: 30rpx;
    bottom: 30rpx;
    z-index: 99;
  }
}
</style> 